import React, {useEffect, useRef, useState} from "react";
import {ProColumns, ProFormSelect, ProTable} from "@ant-design/pro-components";
import {PaymentLogItem} from "@/pages/PaymentLogs/data";
import {Avatar, message, Popconfirm} from "antd";
import {DeleteOutlined, EditOutlined, UserSwitchOutlined} from "@ant-design/icons";
import {ActionType} from "@ant-design/pro-table";
import {deletePaymentLog, queryPaymentLog, updatePaymentLog, updatePaymentRefund} from "@/pages/PaymentLogs/service";
import dayjs from "dayjs";
import {useEmotionCss} from "@ant-design/use-emotion-css";
import UpdateForm from "@/pages/PaymentLogs/components/UpdateForm";
import RefundForm from "@/pages/PaymentLogs/components/RefundForm";
import {queryFamily, queryPayment} from "@/pages/User/Account/settings/components/service";

/**
 * 删除节点
 *
 * @param record
 */
const handleSingleRemove = async (record: PaymentLogItem) => {
  const hide = message.loading('正在删除');
  try {
    const res = await deletePaymentLog({
      key: record.id,
    });
    hide();
    if (res) {
      if (res.status === 'done') {
        message.success(res.message);
        return true;
      } else {
        message.error(res.message);
        return false;
      }
    } else {
      message.error('请求超时，请稍后重试');
      return false;
    }
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

/**
 * 更新节点
 *
 * @param fields
 * @param currentRow
 */

const handleUpdate = async (fields: any, currentRow?: PaymentLogItem) => {
  const hide = message.loading('正在修改');

  try {
    const res = await updatePaymentLog({
      id: currentRow?.id,
      ...fields,
    });
    if(res && res.status === "done" ){
      hide();
      message.success(res.message);
      return true;
    }else {
      hide()
      message.error(res.message);
      return false;
    }
  } catch (error) {
    hide();
    message.error('更新失败，请重试！');
    return false;
  }
};

/**
 * 更新节点
 *
 * @param fields
 * @param currentRow
 */

const handleRefund = async (fields: any, currentRow?: PaymentLogItem) => {
  const hide = message.loading('正在处理');

  try {
    const res = await updatePaymentRefund({
      id: currentRow?.id,
      ...fields,
    });
    if(res && res.status === "done" ){
      hide();
      message.success(res.message);
      return true;
    }else {
      hide()
      message.error(res.message);
      return false;
    }
  } catch (error) {
    hide();
    message.error('更新失败，请重试！');
    return false;
  }
};

export type Props = {
  update: boolean;
};


const PaymentLogs: React.FC<Props> = (props: {update: boolean}) => {
  const actionRef = useRef<ActionType>();
  /** 更新窗口的弹窗 */
  const [currentRow, setCurrentRow] = useState<PaymentLogItem>();
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [refundModalVisible, handleRefundModalVisible] = useState<boolean>(false);

  const paymentClassName = useEmotionCss(() => {
    return {
      color: "green"
    };
  });
  const refundClassName = useEmotionCss(() => {
    return {
      color: "red"
    };
  });

  // 更新流水
  useEffect(() => {
    actionRef.current?.reload()
  }, [props.update]);

  const [dataSource, setDatasource] = useState<any[]>([])
  const [typeDataSource, setTypeDatasource] = useState<any[]>([])

  // 从后台获取用户对象数据
  useEffect(() => {
    queryFamily().then((res)=>{
      if (res.status === "done"){
        // 数据获取成功
        // 整理list为prolist对象
        let data = [...dataSource];

        // 先清空
        data.splice(0, data.length)

        // 填充新数据
        // eslint-disable-next-line array-callback-return
        res.data?.map((item: {name: string, id: number})=>{
          data.push({
            label: item.name,
            value: item.id,
          })
        })
        setDatasource(data)
      }
    })
  }, []);

  // 从后台获取支出分类数据
  useEffect(() => {
    queryPayment().then((res)=>{
      if (res.status === "done"){
        // 数据获取成功
        // 整理list为prolist对象
        let data = [...typeDataSource];

        // 先清空
        data.splice(0, data.length)

        // 填充新数据
        // eslint-disable-next-line array-callback-return
        res.data?.map((item: {name: string, id: number})=>{
          data.push({
            label: item.name,
            value: item.id,
          })
        })
        setTypeDatasource(data)
      }
    })
  }, []);
  const columns: ProColumns<PaymentLogItem>[] = [
    // 按对象搜索
    {
      title: "分类",
      dataIndex: "type",
      valueType: "select",
      hideInTable: true,
      renderFormItem: (_, fieldConfig, form) => {
        if (fieldConfig.type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            // value 和 onchange 会通过 form 自动注入。
            <ProFormSelect
              label={"分类："}
              options={typeDataSource}
            />
          );
        }
        return fieldConfig.defaultRender(_);
      },
    },

    // 按对象搜索
    {
      title: "对象",
      dataIndex: "family",
      valueType: "select",
      hideInTable: true,
      renderFormItem: (_, fieldConfig, form) => {
        if (fieldConfig.type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            // value 和 onchange 会通过 form 自动注入。
            <ProFormSelect
              label={"对象"}
              options={dataSource}
            />
          );
        }
        return fieldConfig.defaultRender(_);
      },
    },

    {
      title: "id",
      dataIndex: "id",
      hideInSearch: true,
      hideInTable: true
    },
    {
      title: "日期",
      dataIndex: "date",
      valueType: "text",
      align: "center",
      hideInSearch: true,
      width: 100,
      render: (_, record) =>{
        if (record.date){
          return record.date
        }return null
      }
    },
    {
      title: "时间",
      dataIndex: "time",
      valueType: "time",
      align: "center",
      hideInSearch: true,
      width: 50,
      render: (_, record)=>(
        dayjs(record.time).format("HH:mm")
      )
    },
    {
      title: "分类",
      dataIndex: "payType",
      valueType: "text",
      align: "center",
      editable: false,
      hideInSearch: true,
      render: (_, record)=>{
        return(
          <>
            <Avatar size={"small"} src={"/static/icons/" + record.payType?.icon}/> {record.payType?.name}
          </>
        )
      }
    },
    {
      title: "金额",
      dataIndex: "money",
      valueType: "money",
      align: "right",
      hideInSearch: true,
      className: paymentClassName,
    },
    {
      title: "退款",
      dataIndex: "refund",
      valueType: "money",
      align: "right",
      hideInSearch: true,
      className: refundClassName,
    },
    {
      title: "对象",
      dataIndex: "familyType",
      valueType: "text",
      align: "center",
      editable: false,
      hideInSearch: true,
      render: (_, record)=> {
        return (
          <>
            <Avatar size={"small"} src={"/static/icons/" + record.familyType?.icon}/> {record.familyType?.name}
          </>
        )
      }
    },
    {
      title: "备注",
      dataIndex: "remark",
      valueType: "text",
      align: "left",
      hideInSearch: true,
    },
    {
      title: "",
      valueType: "option",
      align: "right",
      width: 30,
      render: (_, record)=>[
        <a
          style={{color: "gray"}}
          key={"update"}
          title={"修改流水"}
          onClick={()=>{
            setCurrentRow(record)
            handleUpdateModalVisible(true)
          }}
        ><EditOutlined/></a>,
        <a
          style={{color: "gray"}}
          key={"update"}
          title={"退款"}
          onClick={()=>{
            setCurrentRow(record)
            handleRefundModalVisible(true)
          }}
        ><UserSwitchOutlined /></a>,
        <Popconfirm key="popconfirm" title={`确认删除吗?`} okText="是" cancelText="否" onConfirm={async () => {
          const success = await handleSingleRemove(record);
          if (success) {
            actionRef.current?.reload()
          }
        }}>
          <a style={{color: "gray"}} ><DeleteOutlined /></a>
        </Popconfirm>
      ]
    },
  ];
  return (
    <>
      <ProTable
        scroll={{ y: `calc(100vh - 260px)`, x: `max-content` }}
        defaultSize={"small"}
        actionRef={actionRef}
        columns={columns}
        rowKey={"id"}
        search={{
          filterType: 'light',
        }}
        headerTitle={<b style={{color: "green"}}>支出流水</b>}
        options={false}
        // toolBarRender={false}
        request={queryPaymentLog}
        pagination={{defaultPageSize: 20, pageSizeOptions:[10, 20, 100, 1000, 10000], showSizeChanger: true}}
      />
      <UpdateForm
        onCancel={()=>{
          handleUpdateModalVisible(false)
          setCurrentRow(undefined)
          actionRef.current?.reload()
        }}
        onSubmit={async (value)=>{
          const success = await handleUpdate(value, currentRow);
          if (success){
            handleUpdateModalVisible(false)
            setCurrentRow(undefined)
            // 更新数据
            actionRef.current?.reload()
          }
        }}
        modalVisible={updateModalVisible}
        values={currentRow || {}}
      />
      <RefundForm
        onCancel={()=>{
          handleRefundModalVisible(false)
          setCurrentRow(undefined)
          actionRef.current?.reload()
        }}
        onSubmit={async (value)=>{
          const success = await handleRefund(value, currentRow);
          if (success){
            handleRefundModalVisible(false)
            setCurrentRow(undefined)
            // 更新数据
            actionRef.current?.reload()
          }
        }}
        modalVisible={refundModalVisible}
        values={currentRow || {}}
      />
    </>
  )
}
export default PaymentLogs;
